<template>
    <div class="sreach-container">
        <!-- 搜索栏 -->
        <form action="/">
            <van-search 
                v-model="value" 
                placeholder="请输入搜索关键词" 
                @search="onSearch(value)"
                @cancel="$router.back()"
                show-action
                @focus="isShow=false"
            />
        </form>
        <!-- 搜索栏 -->

        <!-- 搜索结果 -->
        <SearchResult 
            :search-text="value" 
            v-if="isShow"
        />
        <!-- /搜索结果 -->

        <!-- 联想建议 -->
        <SearchSuggestion 
            :search-text="value" 
            v-else-if="value"
        />
        <!-- /联想建议 -->

        <!-- 历史记录 -->
        <SearchHistory 
            :searchHistories="searchHistories" 
            v-else
            @search="onSearch"
            @update-histories="searchHistories = $event"
        />
        <!-- /历史记录 -->
        
    </div>
</template>
<script>
import { setItem,getItem }  from '@/utils/storage'
import SearchSuggestion from './component/search-suggestion.vue'
import SearchHistory from './component/search-history.vue'
import SearchResult from './component/search-result.vue'
export default {
    name:'searchIndex',
    data() {
        return {
            value:'',
            isShow:false,
            searchHistories:getItem('search-histories') || []
        }
    },
    methods:{
        onSearch(value) {

            this.value = value
            const index = this.searchHistories.indexOf(value)
            if(index !== -1){
                this.searchHistories.splice(index,1)
            }
            this.searchHistories.unshift(value)

           // setItem('search-histories',this.searchHistories)

            this.isShow = true;
        }
    },
    components:{
        SearchSuggestion,
        SearchHistory,
        SearchResult
    },
    watch:{
        searchHistories(){
            setItem('search-histories',this.searchHistories)
        }
    }
}
</script>
<style lang="less" scoped>

</style>